package service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import dao.QuestionMapper;
import domain.Question;
import domain.QuestionExample;

/**
 * User: xinxin
 * Date: 2016-11-05
 * Time: 21:46
 * FIXME
 */
@Service
public class QuestionServiceImp implements QuestionServiceI {
    @Autowired
    QuestionMapper mQuestionMapper;

    @Override
    public boolean addQuestion(Question question) {
        return mQuestionMapper.insert(question) > 0;
    }

    @Override
    public List<Question> getRandomQuestions(int randomCount) {
        QuestionExample questionExample = new QuestionExample();
        final QuestionExample.Criteria criteria = questionExample.createCriteria();
        long count = mQuestionMapper.countByExample(questionExample);
        criteria.andIdIn(getRandomIntList(randomCount, (int) count));
        questionExample.or(criteria);
        final List<Question> questions = mQuestionMapper.selectByExample(questionExample);
        if(questions!=null){
            return questions;
        }
        return null;
    }

    /**
     * 获取一个随机数列表,这个列表中不会包含0
     * @param randomCount 获取的随机数个数
     * @param max 随机数的最大值
     */
    private List<Integer> getRandomIntList(int randomCount, int max) {
        List<Integer> ids = new ArrayList<>();
        int c = 1;
        while (c <= randomCount) {
            int random = new Random().nextInt(max);
            if (ids.contains(random)) {
                continue;
            }
            ids.add(random);
            c++;
        }
        return ids;
    }
}
